package com.genius.filter;

import cn.hutool.core.util.StrUtil;
import com.genius.properties.UrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.genius.constant.SecurityConstants.HEADER_AUTH;

@Slf4j
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Autowired
    private UrlProperties urlProperties;

    // 路径匹配的规则器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前的请求路径
        String url = exchange.getRequest().getURI().getPath();
        // 获得所有的需要排除校验的url list
        List<String> excludeList = urlProperties.getExcludeUrls();
        //  校验并且排除excludeList
        if (excludeList != null && !excludeList.isEmpty()) {
            for (String excludeUrl : excludeList) {
                if (antPathMatcher.matchStart(excludeUrl, url)) {
                    // 如果匹配到，则直接放行，表示当前的请求url是不需要被拦截校验的
                    return chain.filter(exchange);
                }
            }
        }
        // 判断header中是否有token，对用户请求进行判断拦截
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst(HEADER_AUTH);
        // 判空header中的令牌
        if (StrUtil.isNotBlank(token)) {
            // 如果匹配到，鉴权成功，则直接放行
            ServerWebExchange serverWebExchange = setNewHeader(exchange, HEADER_AUTH, token);
            return chain.filter(serverWebExchange);
        }
        return chain.filter(exchange);
    }

    private ServerWebExchange setNewHeader(ServerWebExchange exchange, String headerKey, String headerValue) {
        try {
            headerValue = URLEncoder.encode(headerValue, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 重新构建新的request
        ServerHttpRequest newRequest = exchange.getRequest().mutate().header(headerKey, headerValue).build();
        // 替换原来的request
        return exchange.mutate().request(newRequest).build();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}